"""EC200UEU + FCM360W 4G 转 wifi 模块"""

import sim
import checkNet
from network import FCM360W


WIFI_SPI_PORT = 0
WIFI_SPI_PIN = 22
WIFI_SSID = "freewill_4g_wifi"
WIFI_PASSWORD = "123456789"


wifi_obj = None


class WifiActiveError(Exception):
    pass


class WifiConfigError(Exception):
    pass


def initWifiAP():
    global wifi_obj
    wifi_obj = FCM360W(WIFI_SPI_PORT, WIFI_SPI_PIN)
    print("set wifi ssid: \"{}\", password: \"{}\"".format(WIFI_SSID, WIFI_PASSWORD))
    if wifi_obj.config(ssid=WIFI_SSID, password=WIFI_PASSWORD) != 0:
        raise WifiConfigError
    print("wifi activating...")
    if wifi_obj.active(True) != 0:
        raise WifiActiveError


class SimCardNotReady(Exception):
    pass


class NetwordNotReady(Exception):
    pass


def checkSimAndNet():
    print("check sim and net status")
    if not sim.getStatus():
        raise SimCardNotReady
    print("check sim status done, sim card ready...")
    if checkNet.waitNetworkReady(60) != (3, 1):
        raise NetwordNotReady
    print("check net status done, network ready...")


def main():
    try:
        checkSimAndNet()
        initWifiAP()
    except Exception as e:
        print("init wifi got exception: {}".format(type(e).__name__))


if __name__ == '__main__':
    main()
